"""
socket服务端
这段代码是多线程，可接受多次消息
"""
import socket
import threading

def handle_client(conn, addr):
    print(f"Connected by {addr}")
    while True:
        data = conn.recv(1024)
        if not data:
            break
        print("Received:", data.decode())
        # 输入返回的消息
        msg = input("Input your message:")
        if msg == "exit":
            conn.close()
            break
        conn.sendall(msg.encode())
    conn.close()

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(("127.0.0.1", 8888))
s.listen(5)

print("Server is listening...")

while True:
    conn, addr = s.accept()
    # 创建一个线程来处理客户端连接
    thread = threading.Thread(target=handle_client, args=(conn, addr))
    thread.start()
